package ru.jexp.rcp.supply.viewer;

import java.util.List;

import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.TableColumn;

public class JExpTableViewer extends TableViewer {

	public static final int ADD = 0;
	public static final int EDIT = 1;
	public static final int DELETE = 2;

	public JExpTableViewer(Composite parent) {
		this(parent, null);
	}

	public JExpTableViewer(Composite parent, JExpTableLabelProvider provider) {
		super(parent, SWT.FULL_SELECTION);
		getTable().setHeaderVisible(true);
		getTable().setLinesVisible(true);
		setContentProvider(new JExpContentProvider());
		if (provider != null) {
			setJExpTableLabelProvider(provider);
		}
	}

	public final void setJExpTableLabelProvider(JExpTableLabelProvider provider) {
		setLabelProvider(provider);
		setComparator(new JExpTableViewerComparator());
		createColumn(provider);
	}

	public final List<?> getValue() {
		return (List<?>) getInput();
	}

	public StructuredSelection getStructuredSelection() {
		return (StructuredSelection) getSelection();
	}

	public void setLayoutData(Object layoutData) {
		getTable().setLayoutData(layoutData);
	}

	public void updateViewer(int action, Object object) {
		switch (action) {
		case JExpTableViewer.ADD:
			add(object);
			break;
		case JExpTableViewer.EDIT:
			update(object, null);
			break;
		case JExpTableViewer.DELETE:
			remove(object);
			break;
		}
	}

	@Override
	protected void inputChanged(Object input, Object oldInput) {
		super.inputChanged(input, oldInput);
		pack();
	}

	private void pack() {
		for (TableColumn column : getTable().getColumns()) {
			column.pack();
		}

	}

	private void createColumn(JExpTableLabelProvider provider) {
		for (int i = 0; i < provider.getColumnsSize(); i++) {
			final TableColumn tableColumn = new TableColumn(getTable(),
					SWT.NONE);
			tableColumn.setWidth(200);
			tableColumn.setText(provider.getColumnName(i));
			tableColumn.setToolTipText(provider.getColumnName(i));
			tableColumn.setMoveable(true);
			tableColumn.setResizable(true);
			tableColumn.pack();
			tableColumn.addSelectionListener(new SelectionAdapter() {
				@Override
				public void widgetSelected(SelectionEvent e) {
					JExpTableViewerComparator comparetor = (JExpTableViewerComparator) JExpTableViewer.this
							.getComparator();
					if (comparetor != null) {
						comparetor.setCurrentColumn(tableColumn.getText());
						JExpTableViewer.this.getTable().setSortDirection(
								comparetor.getDirection());
						JExpTableViewer.this.getTable().setSortColumn(
								tableColumn);
						JExpTableViewer.this.refresh();
					}
				}
			});
		}
	}
}
